package infocluster.task;

import infocluster.prototype.ExcelProcessTask;
import infocluster.util.Utility;

import java.io.IOException;

import jxl.*;
import jxl.write.*;
import jxl.write.biff.RowsExceededException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReshapeProcessTask extends ExcelProcessTask{
	
	private static final int COLUMN = 24;
	private static final int HEADER_EN = 0;
	private static final int HEADER_CN = 1;
	
	private static final String PARTNER_STR = "Hot Pepper";
	private static final String CONTACT_NAME_STR = "Xiao Long";
	private static final String CONTACT_PHONE_STR = "63343117*2922";
	private static final String CONTACT_EMAIL_STR = "longjiaqi@rgf-china.com";
	
	private static final int PARTNER = -2;
	private static final int CONTACT_NAME = -3;
	private static final int CONTACT_PHONE = -4;
	private static final int CONTACT_EMAIL = -5;
	private static final int NONE = -1;
	private static final int OUTLET_NAME_BREAK = 7;
	private static final int CATEGORY_TRANS = 3;
	private static final int NOTHING = 0;
	private static final int CITY_TRANS = 2;
	private static final int DISTRICT_TRANS = 5;
	private static final int PHONE_CLEAN = 10;
	private static final int HL_CLEAN = 18;
	
	@SuppressWarnings("unused")
	private static final int COLUMN_OFFER = 14;
	
	private static final String[] COLUMN_EN = {"merchant_name_en",
		"merchant_name_Chinese","category","partner","contact_name",
		"contact_phone_number","contact_email","merchant_website_url",
		"merchant_description_en","merchant description_zh","outlet_name_en",
		"outlet_name","city","address_en","address_cn","district",
		"phone_number","offer_name_en","offer_name_zh","offer_highlight_en",
		"offer_highlight_zh","terms_and_conditions",
		"terms_and_conditions_chinese","hot_promotion"};
	
	private static final String[] COLUMN_CN = {"商户名","商家名（中文名）","类型",
		"合作伙伴","联系人","联系人电话","联系人邮箱","商户网址","商户简介",
		"商户简介（中文）","分店名","分店名（中文）","城市","地址","地址（中文）"
		,"行政区","电话","优惠主题","优惠主题（中文）","优惠信息详细",
		"优惠信息详细（中文）","使用条件","使用条件（中文）","是否热门优惠"};
	
	private static final int[] CORRES_COLUMN = {-1,7,3,-2,-3,-4,-5,-1,-1,8,-1,
		0,2,-1,9,5,10,-1,14,-1,18,-1,15,-1};

	public boolean execute() throws IOException{
		try {
			System.out.println(this.getSource(0));
			Workbook wb = Workbook.getWorkbook(this.getSource(0));
			WritableWorkbook newWb = Workbook.createWorkbook(this.getDest(0));
			
			Sheet sheet = wb.getSheet(0);
			int rowCount = sheet.getRows();
			int columnCount = COLUMN;
			
			WritableSheet newSheet = newWb.createSheet("offers", 0);
			
			int i;
			
			for(i=0;i<columnCount;i++){
				Label label = new Label(i, HEADER_EN, COLUMN_EN[i]); 
				//label.setCellFormat(cf);
				newSheet.addCell(label); 
			}
			
			for(i=0;i<columnCount;i++){
				Label label = new Label(i, HEADER_CN, COLUMN_CN[i]); 
				//label.setCellFormat(cf);
				newSheet.addCell(label); 
			}
			
			for(i=1;i<rowCount;i++){
				for(int j=0;j<columnCount;j++){					
					int column = CORRES_COLUMN[j];
					buildCell(sheet, newSheet, i, j, column);
				}				
			}
			
			newWb.write(); 
			newWb.close();
			
			wb.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * @param sheet
	 * @param i
	 * @param j
	 * @param column
	 * @return
	 * @throws WriteException 
	 * @throws RowsExceededException 
	 */
	@SuppressWarnings("deprecation")
	private void buildCell(Sheet sheet, WritableSheet newSheet, int i, int j, int column) throws RowsExceededException, WriteException {
		Label label = new Label(j, i+1, "");
		
		switch(column){
			case PARTNER:{
				label = new Label(j, i+1, PARTNER_STR);
			}
			break;
			case CONTACT_NAME:{
				label = new Label(j, i+1, CONTACT_NAME_STR);
			}
			break;
			case CONTACT_PHONE:{
				label = new Label(j, i+1, CONTACT_PHONE_STR);
			}
			break;
			case CONTACT_EMAIL:{
				label = new Label(j, i+1, CONTACT_EMAIL_STR);
			}
			break;
			case NONE:{
				label = new Label(j, i+1, "");
			}
			break;
			case OUTLET_NAME_BREAK:{
				String content = sheet.getCell(column, i).getContents();
				content = content.replace("（","(").replace("）", ")");
				
				int leftBrace = content.indexOf("(");
				int rightBrace = content.indexOf(")");
				int alias = content.indexOf("别名");
				
				String[] clip = {"","",""};
				if(alias != -1){
					clip[2] = content.substring(alias+3).trim();
					content = content.substring(0, alias);
				}
				
				if(leftBrace != -1){
					clip[0] = content.substring(0, leftBrace).trim();
					clip[1] = content.substring(leftBrace+1, rightBrace).trim();
				}else{
					clip[0] = content.trim();
				}

				if(!clip[1].startsWith("原")){
					label = new Label(11, i+1, clip[1]);
				}else{
					label = new Label(11, i+1, "");
				}
				if((clip[1].equals("")) || (clip[1].startsWith("原"))){
					WritableCellFormat cf = new WritableCellFormat(label.getCellFormat());
					cf.setBackground(Colour.YELLOW);
					label.setCellFormat(cf);
				}
				newSheet.addCell(label);
								
				label = new Label(j, i+1, clip[0]);				
			}
			break;
			case CATEGORY_TRANS:{
				String content = sheet.getCell(column, i).getContents().trim();
				label = new Label(j, i+1, Utility.getCategory(content));
				if(content.equals("")){
					WritableCellFormat cf = new WritableCellFormat(label.getCellFormat());
					cf.setBackground(Colour.YELLOW);
					label.setCellFormat(cf);
				}
			}
			break;
			case NOTHING:{
				// do nothing
				return;
			}
			case CITY_TRANS:{
				String content = sheet.getCell(column, i).getContents().trim();
				label = new Label(j, i+1, Utility.getCity(content));
				if(content.equals("")){
					WritableCellFormat cf = new WritableCellFormat(label.getCellFormat());
					cf.setBackground(Colour.YELLOW);
					label.setCellFormat(cf);
				}
			}
			break;
			case DISTRICT_TRANS:{
				String content = sheet.getCell(column, i).getContents().trim();
				label = new Label(j, i+1, Utility.getDistrict(content));
				if(content.equals("")){
					WritableCellFormat cf = new WritableCellFormat(label.getCellFormat());
					cf.setBackground(Colour.YELLOW);
					label.setCellFormat(cf);
				}
			}
			break;
			case PHONE_CLEAN:{
				String content = sheet.getCell(column, i).getContents().trim();
				int sp = content.indexOf(" ");
				int hp = content.indexOf("-");
				if(sp != -1){
					if(hp != -1){
						content = content.substring(hp+1,sp);
					}else{
						content = content.substring(0,sp);
					}					
				}
				label = new Label(j, i+1, content);
			}
			break;
			case HL_CLEAN:{
				String content = sheet.getCell(column, i).getContents().trim();
				content = getHighlight(content.substring(5));
				label = new Label(j, i+1, content);
				if(content.equals("")){
					WritableCellFormat cf = new WritableCellFormat(label.getCellFormat());
					cf.setBackground(Colour.YELLOW);
					label.setCellFormat(cf);
				}
			}
			break;
			default:{
				Cell c = sheet.getCell(column, i);
				label = new Label(j, i+1, c.getContents());
			}
		}
		
		newSheet.addCell(label); 
	}
	
	private String getHighlight(String str){
		
		Pattern pat = Pattern.compile("(\\d{2,4}(\\.|年))*\\d{1,2}(\\.|月)\\d{1,2}(日)*");

	    Matcher mat = pat.matcher(str);
	    String newStr = "";

	    while (mat.find()){
	    	newStr = "有效期至" + mat.group();
	    }
		
		return newStr;		
	}
}
